local _G = _G
local addon, ns = ...
local profile = ns.profile
local cfg = {}
local noshow
local GetTalentId
local SaveVars
local addonprofile
if not _G.LabelUI_mod then
	_G.LabelUI_mod = {}	
end
  
local Tidyplatesmod = CreateFrame("Frame", nil, UIParent)
--END LabelUI declaration

--Start tidyplates declaration
--TidyPlates_Quatre remake
local Theme = {}

local path = "Interface\\Addons\\LabelUI_AddOns\\media\\"
local font = "Interface\\Addons\\LabelUI\\media\\Aquarion.otf"

local castbarVertical = -15

local StyleDefault = {}

StyleDefault.frame = {
	width = 100,
	height = 45,
	x = 0,
	y = 0,		
	anchor = "CENTER",
}

StyleDefault.healthborder = {
	texture		 =					path.."RegularBorder2",
	width = 128,
	height = 64,
	x = 0,
	y = 0,
	anchor = "CENTER",
}

StyleDefault.target = {
	texture		 =				path.."TargetBox2",
	width = 128,
	height = 64,
	x = 0,
	y = 0,
	anchor = "CENTER",
	show = true,
}

StyleDefault.highlight = {
	texture		 =					path.."RegularBorder2",
}

StyleDefault.threatborder = {
	texture =			path.."RegularThreatLarger",
	width = 128,
	height = 64,
	x = 0,
	y = 0,
	anchor = "CENTER",
}

StyleDefault.castbar = {
	texture =					path.."Statusbar",
	backdrop = 				path.."Empty",
	height = 8,
	width = 99,
	x = 0,
	y = 15+castbarVertical,
	anchor = "CENTER",
	orientation = "HORIZONTAL",
}

StyleDefault.castborder = {
	texture =					path.."RegularBorder2",
	width = 128,
	height = 64,
	x = 0,
	y = castbarVertical,
	anchor = "CENTER",
}

StyleDefault.castnostop = {
	texture = 				path.."RegularBorder3",
	width = 128,
	height = 64,
	x = 0,
	y = castbarVertical,
	anchor = "CENTER",
}

StyleDefault.name = {
	typeface =					font,
	size = 12,
	height = 12,
	width = 180,
	x = 0,
	y = 9,
	align = "CENTER",
	anchor = "TOP",
	vertical = "BOTTOM",
	shadow = true,
	flags = "NONE",
}

StyleDefault.level = {
	typeface =					font,
	size = 11,
	width = 93,
	height = 10,
	x = -2,
	y = 14.85,
	align = "LEFT",
	anchor = "CENTER",
	vertical = "BOTTOM",
	shadow = true,
	flags = "NONE",
	show = false,
}

StyleDefault.healthbar = {
	texture =					 path.."Statusbar",
	backdrop = 				path.."StatusbarBackground40",
	height = 8.5,
	width = 98.5,
	x = 0,
	y = 15,
	anchor = "CENTER",
	orientation = "HORIZONTAL",
}

StyleDefault.customtext = {
	typeface =					font,
	size = 9,
	width = 93,
	height = 10,
	x = 0,
	y = 16,
	align = "RIGHT",
	anchor = "CENTER",
	vertical = "BOTTOM",
	shadow = true,
	flags = "NONE",
	show = true,
}

StyleDefault.spelltext = {
	typeface =					font,
	size = 12,
	height = 12,
	width = 180,
	x = 0,
	y = -11 + castbarVertical,
	align = "CENTER",
	anchor = "TOP",
	vertical = "BOTTOM",
	shadow = true,
	flags = "NONE",
	show = true,
}

StyleDefault.spellicon = {
	width = 25,
	height = 25,
	x = -67,
	y = 22+castbarVertical,
	anchor = "CENTER",
}

StyleDefault.eliteicon = {
	texture = path.."RegularBorder2", 
	width = 128,
	height = 64,
	x = 0,
	y = 0,
	anchor = "CENTER",
	show = true,
}

StyleDefault.raidicon = {
	width = 25,
	height = 25,
	x = -55,
	y = 21,
	anchor = "CENTER",
}

StyleDefault.skullicon = {
	width = 8,
	height = 8,
	x = 2,
	y = 15,
	anchor = "LEFT",
}

StyleDefault.threatcolor = {
	LOW = {r = .6, g = 1, b = 0, a = 0,},
	MEDIUM = {r = .6, g = 1, b = 0, a = 1,},
	HIGH = {r = 1, g = 0, b = 0, a= 1,},  }

	
-- No-Bar Style		(6.2)
local StyleTextOnly
local ThemeTest
local WidgetConfig
local DamageThemeName
local TankThemeName

local LocalVars

local ApplyThemeCustomization

local function ApplyDamageCustomization()
	ApplyThemeCustomization(Theme)
end

local fraction, range, value, barsize

local function UpdateBar(self, svalue)
	local cursvalue
	range = self.MaxVal - self.MinVal 
	if svalue then 
		cursvalue = svalue
		self.ValueReal = svalue 
	else
		self.ValueReal = self.Value
	end 
	value = self.ValueReal  - self.MinVal

	barsize = self.Dim or 1

	if range > 0 and value > 0 and range >= value then
		fraction = value / range
	else fraction = .01 end
	if self.Orientation == "VERTICAL" then 
		self.Bar:SetHeight(barsize * fraction)
		self.Bar:SetTexCoord(0, 1, 1-fraction, 1)
	else 
		self.Bar:SetWidth(barsize * fraction) 
		self.Bar:SetTexCoord(0, fraction, 0, 1)
	end
end


local smoothing = {}
local function Smooth(self, value)
	local max = self.MaxVal
	if value == self._value or (self._max and self._max ~= max) then
		smoothing[self] = nil
		UpdateBar(self)
	else
		smoothing[self] = value
	end
	self._max = max
	self._value = value
end

local f, min, max = CreateFrame('Frame'), math.min, math.max 
f:SetScript('OnUpdate', function()
	local limit = 30/GetFramerate()
	for bar, value in pairs(smoothing) do
		local cur = bar.ValueReal
		local new = cur + min((value-cur)/3, max(value-cur, limit))
		if new ~= new then
			new = value
		end
		UpdateBar(bar, new) 
		if cur == value or abs(new - value) < 2 then
			UpdateBar(bar)
			smoothing[bar] = nil
		end
	end
end)

local function UpdateSize(self)
	if self.Orientation == "VERTICAL" then self.Dim = self:GetHeight()
	else self.Dim = self:GetWidth() end
	UpdateBar(self)
end

local function SetValue(self, value) 
	if value >= self.MinVal and value <= self.MaxVal then self.Value = value end; 
	Smooth(self, value)
end

local function SetOrientation(self, orientation) 
	if orientation == "VERTICAL" then
		self.Orientation = orientation
		self.Bar:ClearAllPoints()
		self.Bar:SetPoint("BOTTOMLEFT")
		self.Bar:SetPoint("BOTTOMRIGHT")
	else
		self.Orientation = "HORIZONTAL"
		self.Bar:ClearAllPoints()
		self.Bar:SetPoint("TOPLEFT")
		self.Bar:SetPoint("BOTTOMLEFT")
	end
	UpdateSize(self)
end

local function SetMinMaxValues(self, minval, maxval)
	if not (minval or maxval) then return end
	
	if maxval > minval then
		self.MinVal = minval
		self.MaxVal = maxval
	else 
		self.MinVal = 0
		self.MaxVal = 1
	end
	
	if self.Value > self.MaxVal then self.Value = self.MaxVal
	elseif self.Value < self.MinVal then self.Value = self.MinVal end
	
	UpdateBar(self) 
end

local function OnInitialize(plate)
	if plate.bars.healthbar and not plate.bars.healthbar.luiupdated then
		plate.bars.healthbar.SetValue = SetValue
		plate.bars.healthbar.SetMinMaxValues = SetMinMaxValues
		plate.bars.healthbar.SetOrientation = SetOrientation
		plate.bars.healthbar.luiupdated = true
	end
	if plate.visual and plate.visual.spellicon then
		if not plate.visual.spellicon.bg then
			plate.visual.spellicon.bg = plate.visual.spellicon:GetParent():CreateTexture(nil, "ARTWORK")
			plate.visual.spellicon.bg:SetTexture(path.."Spellborder")
			plate.visual.spellicon.bg:SetPoint("TOPLEFT", plate.visual.spellicon, "TOPLEFT", -2, 2) 
			plate.visual.spellicon.bg:SetPoint("BOTTOMRIGHT", plate.visual.spellicon, "BOTTOMRIGHT", 2, -2) 
			plate.visual.spellicon:SetTexCoord(0.1,0.9,0.1,0.9)
			plate.visual.spellicon.SetTexCoord = noshow
		end
	end
	TidyPlatesHubFunctions.OnInitializeWidgets(plate, WidgetConfig)
end

local function OnActivateTheme(themeTable)
		if Theme == themeTable then
			LocalVars = TidyPlatesHubFunctions:UseDamageVariables()
			ApplyDamageCustomization()
		end
end


  
local function Enablemod()
--[[			START 			]]--

	LocalVars = TidyPlatesHubDamageVariables
	ApplyThemeCustomization = TidyPlatesHubFunctions.ApplyThemeCustomization
	DamageThemeName = "LabelUI/|cFFFF4400Damage"
	TankThemeName = "LabelUI/|cFF3782D1Tank"
	
	local CopyTable = TidyPlatesUtility.copyTable
	
	StyleTextOnly = CopyTable(StyleDefault)
	StyleTextOnly.threatborder.texture = EmptyTexture
	StyleTextOnly.healthborder.texture = EmptyTexture
	StyleTextOnly.healthbar.texture = EmptyTexture
	StyleTextOnly.healthbar.backdrop = EmptyTexture
	StyleTextOnly.eliteicon.texture = EmptyTexture
	StyleTextOnly.customtext.align = "CENTER"
	StyleTextOnly.customtext.size = 10
	StyleTextOnly.customtext.y = 16
	StyleTextOnly.level.show = false
	StyleTextOnly.skullicon.show = false
	StyleTextOnly.eliteicon.show = false
	StyleTextOnly.highlight.texture = path.."TextPlate_Highlight"
	StyleTextOnly.target.texture = path.."TextPlate_Target"
	ThemeTest = CopyTable(StyleDefault)
	ThemeTest.threatborder.texture = EmptyTexture
	ThemeTest.healthborder.texture = EmptyTexture
	ThemeTest.healthbar.texture = EmptyTexture
	ThemeTest.healthbar.backdrop = EmptyTexture
	ThemeTest.eliteicon.texture = EmptyTexture
	ThemeTest.name.size = 18
	ThemeTest.name.height = 20
	ThemeTest.name.width = 250
	ThemeTest.name.x = 0
	ThemeTest.name.y = 9
	ThemeTest.name.flags = "OUTLINE"
	ThemeTest.customtext.align = "CENTER"
	ThemeTest.customtext.size = 10
	ThemeTest.customtext.y = 16
	ThemeTest.customtext.show = false
	ThemeTest.level.show = false
	ThemeTest.skullicon.show = false
	ThemeTest.eliteicon.show = false
	ThemeTest.highlight.texture = path.."TextPlate_Highlight"
	ThemeTest.target.texture = path.."TextPlate_Target"

	WidgetConfig = {}
	WidgetConfig.ClassIcon = { anchor = "TOP" , x = 0,y = 26 }		-- Above Name
	WidgetConfig.TotemIcon = { anchor = "TOP" , x = 0 ,y = 26 }
	WidgetConfig.ThreatLineWidget = { anchor =  "TOP", x = 0 ,y = 20 }	-- y = 20
	WidgetConfig.ThreatWheelWidget = { anchor =  "CENTER", x = 33 ,y = 27 } -- "CENTER", plate, 30, 18
	WidgetConfig.ComboWidget = { anchor = "TOP" , x = 0 ,y = 0 }
	WidgetConfig.RangeWidget = { anchor = "CENTER" , x = 0 ,y = 12 }
	WidgetConfig.DebuffWidget = { anchor = "TOP" , x = 15 ,y = 33 }
	
	Theme["Default"] = StyleDefault
	Theme["NameOnly"] = StyleTextOnly			-- (6.2)

	TidyPlatesThemeList[DamageThemeName] = Theme
	
	Theme.SetNameColor = TidyPlatesHubFunctions.SetNameColor
	Theme.SetScale = TidyPlatesHubFunctions.SetScale
	Theme.SetAlpha = TidyPlatesHubFunctions.SetAlpha
	Theme.SetHealthbarColor = TidyPlatesHubFunctions.SetHealthbarColor
	Theme.SetThreatColor = TidyPlatesHubFunctions.SetThreatColor
	Theme.SetCastbarColor = TidyPlatesHubFunctions.SetCastbarColor
	Theme.SetCustomText = TidyPlatesHubFunctions.SetCustomText
	Theme.OnUpdate = TidyPlatesHubFunctions.OnUpdate
	Theme.OnContextUpdate = TidyPlatesHubFunctions.OnContextUpdate
	Theme.ShowConfigPanel = ShowTidyPlatesHubDamagePanel
	Theme.SetStyle = TidyPlatesHubFunctions.SetStyleBinary
	Theme.SetCustomText = TidyPlatesHubFunctions.SetCustomTextBinary
	Theme.OnInitialize = OnInitialize		-- Need to provide widget positions
	Theme.OnActivateTheme = OnActivateTheme -- called by Tidy Plates Core, Theme Loader
	Theme.OnApplyThemeCustomization = ApplyDamageCustomization

	local TankTheme = CopyTable(Theme)
	TidyPlatesThemeList[TankThemeName] = TankTheme
	
	local function ApplyTankCustomization()
		ApplyThemeCustomization(TankTheme)
	end

	local function OnActivateTheme(themeTable)
		if TankTheme == themeTable then
			LocalVars = TidyPlatesHubFunctions:UseTankVariables()
			ApplyTankCustomization()
		end
	end
	
	TankTheme.OnActivateTheme = OnActivateTheme -- called by Tidy Plates Core, Theme Loader
	TankTheme.OnApplyThemeCustomization = ApplyTankCustomization -- Called By Hub Panel
	TankTheme.ShowConfigPanel = ShowTidyPlatesHubTankPanel
	
	
	-- Becouse we added theme table only after PLAYER_LOGIN (our init function) and tidyplates first atemp to load happend at ACTIVE_TALENT_GROUP_CHANGED it try to load
	-- a nil table and thats why replace config var by "none", we fix this by updating var. Didn't need to load theme manualy after update becouse next atemp to load profile tidy made at 
	-- PLAYER_ENTERING_WORLD what happend after our Init function
	local saved_theme_name = SaveVars:Get("Addons_TP_["..addonprofile.."]|spec_"..GetTalentId(), "none")
	if saved_theme_name == DamageThemeName or saved_theme_name == TankThemeName then
		if GetTalentId() == 2 then 
			TidyPlatesOptions["secondary"] = saved_theme_name   
		else
			TidyPlatesOptions["primary"] = saved_theme_name
		end
		--TidyPlates.LoadTheme(saved_theme_name)  
	end
--[[			END 			]]--
end 

Tidyplatesmod:SetScript("OnEvent", function(self, event, arg1)
	--save tidy spec config for fix what has writen above.  
	SaveVars:Set("Addons_TP_["..addonprofile.."]|spec_1", TidyPlatesOptions["primary"])
	SaveVars:Set("Addons_TP_["..addonprofile.."]|spec_2", TidyPlatesOptions["secondary"])
	Tidyplatesmod:UnregisterEvent("PLAYER_LEAVING_WORLD")
end)
  
local function Init()
	_, _, _, enabled, _, reason = GetAddOnInfo("TidyPlates")
	if reason == "MISSING" or not enabled then return end
	Tidyplatesmod:RegisterEvent("PLAYER_LEAVING_WORLD")
	Enablemod()
end

function Tidyplatesmod.InitMod(main, profilename)
	addonprofile = profilename
	if not profile[profilename] then
		for i,v in pairs(profile) do
			if type(i) == "string" then
				profilename = i
				break
			end
		end
	end
	for i,v in pairs(profile[profilename].tidyplates) do
		cfg[i] = v		
	end
	noshow = main.noshow 
	SaveVars = main.SaveVars
	GetTalentId = main.GetTalentId
	
	main:AddInit(Init, "Addon TidyPlatesMod")
end 
  
_G.LabelUI_mod["Tidyplatesmod"] = Tidyplatesmod